//
//  SEGOldRegisterViewController.m
//  Commom
//
//  Created by Clavis on 2020/6/28.
//

#import "SEGOldRegisterViewController.h"
#import "SEGRegisterLeftView.h"
#import <SEGViewModel/SEGSettingPasswordViewModel.h>
#import <SEGViewModel/SEGOldRegisterViewModel.h>

@interface SEGOldRegisterViewController () <RegiserProtocol, UIScrollViewDelegate>

@property (nonatomic, strong) SEGRegisterLeftView *registerView;

/// viewModel
@property (nonatomic, strong) SEGSettingPasswordViewModel *passwordRuleViewModel;
@property (nonatomic, strong) SEGOldRegisterViewModel *oldRegisterViewModel;

@end

@implementation SEGOldRegisterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navDisplayType = SEGNavigationBarDisplayTypeHide;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShowChangeFrame:) name:UIKeyboardWillShowNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHideChangeFrame:) name:UIKeyboardWillHideNotification object:nil];
    
    [self.view addSubview:self.registerView];
    self.registerView.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight());
    // 刷新图片验证码
    [self freshCheckImg];
    // 请求密码规则
    [self requestPasswordConfig];
    [self.registerView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.edges.equalTo(self.view);
    }];
    
    //注册通知 监听用户截屏
    [[NSNotificationCenter defaultCenter] addObserver:self
                                            selector:@selector(handleUserDidTakeScreenshot:)
                                                name:UIApplicationUserDidTakeScreenshotNotification object:nil];

    if (@available(iOS 11.0, *)) {
       // 监测当前设备是否处于录屏状态
       if ([UIScreen mainScreen].isCaptured) {
           dispatch_after(1, dispatch_get_main_queue(), ^{
                [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
           });
       }
       // 监听用户是否录屏
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleScreenCapturedDidChange:) name:UIScreenCapturedDidChangeNotification object:nil];
    }
    
    [self seg_addBottomBrand];
}

/// 截屏处理
- (void)handleUserDidTakeScreenshot:(NSNotification *)notification {
    [SEGAlertView showTmepMessageWithMessage:KDetectScreenShotTipMessage withtime:2];
}

/// 录屏处理
- (void)handleScreenCapturedDidChange:(NSNotification *)notification {
    NSLog(@"%s %@", __func__, notification);
    if (@available(iOS 11.0, *)) {
        if ([UIScreen mainScreen].isCaptured) {
            [SEGAlertView showTmepMessageWithMessage:KDetectScreenCapturedTipMessage withtime:2];
        }
    }
}

#pragma mark - handle

// 请求密码配置
- (void)requestPasswordConfig {
    WeakSelf;
    [self.passwordRuleViewModel.reqConfigSignal subscribeNext:^(id result) {
        if ([result isKindOfClass:[NSString class]]) {
            NSMutableParagraphStyle *paragraphStyle = [NSMutableParagraphStyle new];
            UIFont *font = weakSelf.registerView.passwordRuleLabel.font;
            paragraphStyle.lineSpacing = 6 - (font.lineHeight - font.pointSize);
            paragraphStyle.alignment = NSTextAlignmentRight;
            NSMutableDictionary *attributes = [NSMutableDictionary dictionary];
            [attributes setObject:paragraphStyle forKey:NSParagraphStyleAttributeName];
            weakSelf.registerView.passwordRuleLabel.attributedText = [[NSAttributedString alloc] initWithString:result attributes:attributes];
        }
    }];
}

#pragma mark - RegiserProtocol delegate
/// 完成按钮的点击代理方法
- (void)nextClick:(NSDictionary*)params {
    // 【等保改造】先校验密码是否符合规则
    [SVProgressHUD show];
    [[self.passwordRuleViewModel.vaildCommand execute:[params valueForKey:@"password"]] subscribeNext:^(id  _Nullable x) {
        // 校验密码规则成功后 再校验短信验证码
        [[self.oldRegisterViewModel.messageValidateCommand execute:RACTuplePack([params valueForKey:@"tel"], [params valueForKey:@"smsCode"])] subscribeNext:^(id  _Nullable x) {
            [SVProgressHUD dismiss];
            NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:params];
            NSString *randomToken = x ?: @"";
            [dic setObject:randomToken forKey:@"randomToken"];
            [dic setObject:@(YES) forKey:@"isFromLogin"];
            UIViewController *VC = [[SEGUhomeMediator sharedInstance]
                                    seg_initSelectCommunityViewController:dic];
            [self.navigationController pushViewController:VC animated:YES];
        } error:^(NSError * _Nullable error) {
            [SVProgressHUD dismiss];
            [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
        }];
   } error:^(NSError * _Nullable error) {
       [SVProgressHUD dismiss];
       [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason withtime:1.5];
   }];
}

/// 更新图形验证码
- (void)freshCheckImg {
    @weakify(self);
    self.registerView.checkImgText.text = @"";
    // 提交按钮置灰
    self.registerView.nextButton.enabled = NO;
    [self.oldRegisterViewModel.refreshImgSignal subscribeNext:^(UIImage *decodedImage) {
        @strongify(self);
        if (decodedImage) {
            [self.registerView.checkImgView setImage:decodedImage];
        } else {
            [self.registerView.checkImgView setImage:[UIImage imageWithContentsOfFile:SEGPicName(@"pic_default_72_72")]];
        }
    } error:^(NSError * _Nullable error) {
        [SEGAlertView showTmepMessageWithMessage:error.localizedFailureReason];
    }];
}

/// 获取短信验证码
- (void)getMessage:(NSDictionary*)params {
    [SVProgressHUD show];
    [[self.oldRegisterViewModel.getMessageCommand execute:RACTuplePack([params valueForKey:@"tel"], self.registerView.checkImgText.text)] subscribeNext:^(id  _Nullable x) {
        [SVProgressHUD dismiss];
        [self.registerView sentPhoneCodeTimeMethod];
        [SEGAlertView showTmepMessageWithMessage:@"验证码已发送"];
    } error:^(NSError * _Nullable error) {
        [SVProgressHUD dismiss];
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
        // 短信验证码失败清空&刷新图形验证码
        self.registerView.checkText.text = @"";
        // 提交按钮置灰
        self.registerView.nextButton.enabled = NO;
        [self freshCheckImg];
    }];
}

/// 获取语音验证码
- (void)getSoundMessageWithTel:(NSString*)tel type:(NSString*)type {
    @weakify(self);
    [SVProgressHUD show];
    [[self.oldRegisterViewModel.getSoundMessageCommand execute:RACTuplePack(tel, self.registerView.checkImgText.text, type)] subscribeNext:^(id  _Nullable x) {
        @strongify(self);
        [SVProgressHUD dismiss];
        [self.registerView sentPhoneCodeTimeMethod];
        [SEGAlertView showTmepMessageWithMessage:x withtime:1];
    } error:^(NSError * _Nullable error) {
        @strongify(self);
        [SVProgressHUD dismiss];
        // 语音验证码失败清空&刷新图形验证码
        self.registerView.checkImgText.text = @"";
        // 提交按钮置灰
        self.registerView.nextButton.enabled = NO;
        [self freshCheckImg];
        [SEGAlertView showTmepMessageWithMessage:error.localizedDescription];
    }];
}

/// 提示用户，去登陆
- (void)GotoLogin {
    [self.navigationController popViewControllerAnimated:YES];
}

/// 注册页返回到登录页
- (void)goBackBtnToLoginClick {
    [self.navigationController popViewControllerAnimated:YES];
}

#pragma mark - UIKeyboardShowNotification
- (void)keyboardWillShowChangeFrame:(NSNotification*)notification {
    NSDictionary* info = [notification userInfo];
    CGSize kbSize = [[info objectForKey:UIKeyboardFrameEndUserInfoKey] CGRectValue].size;
    if (CGRectGetMinY(self.view.frame) < 0) {
        return;
    }
    //保证最下面的控件不被遮挡
    CGFloat bottomY = LYScreenHeight();
    if ([UIScreen mainScreen].bounds.size.height == 480 || [UIScreen mainScreen].bounds.size.height ==  568.0f) {
        bottomY = CGRectGetMaxY(self.registerView.gotoLogin.frame) + CGRectGetMinY(self.view.frame);
    }
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        if ([UIScreen mainScreen].bounds.size.height == 480 || [UIScreen mainScreen].bounds.size.height ==  568.0f) {
            self.view.frame = CGRectMake(0, -kbSize.height + (LYScreenHeight() - bottomY), CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
        }else{
            self.view.frame = CGRectMake(0, 0, LYScreenWidth(), LYScreenHeight());
        }
    }];
}
- (void)keyboardWillHideChangeFrame:(NSNotification*)notification {
    NSDictionary* info = [notification userInfo];
    NSTimeInterval duration = [[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] doubleValue];
    [UIView animateWithDuration:duration animations:^{
        self.view.frame = CGRectMake(0, 0, CGRectGetWidth(self.view.bounds), CGRectGetHeight(self.view.bounds));
    }];
}

- (void)touchesBegan:(NSSet<UITouch*>*)touches withEvent:(UIEvent*)event {
    [self.view endEditing:YES];
}

#pragma mark - Getter
- (SEGRegisterLeftView *)registerView {
    if (!_registerView) {
        _registerView = [[SEGRegisterLeftView alloc] init];
        _registerView.delegate = self;
    }
    return _registerView;
}

- (SEGSettingPasswordViewModel *)passwordRuleViewModel {
    if (!_passwordRuleViewModel) {
        _passwordRuleViewModel = [[SEGSettingPasswordViewModel alloc] init];
    }
    return _passwordRuleViewModel;
}

- (SEGOldRegisterViewModel *)oldRegisterViewModel {
    if (!_oldRegisterViewModel) {
        _oldRegisterViewModel = [[SEGOldRegisterViewModel alloc] init];
    }
    return _oldRegisterViewModel;
}

@end
